package cn.kgc.mybatis.jdbc;

import cn.kgc.mybatis.entity.User;
import com.mysql.jdbc.Driver;

import java.sql.*;
import java.util.ArrayList;

/**
 * @author 课工场
 * @date 2024/4/20
 * @description  jdbc连接数据库分析
 *
 * 步骤：
 *  1. 导包  mysql-connector-java  驱动  JDBC 接口实现类 面向接口
 *  2.注册驱动
 *  3.获取连接
 *  4.获取执行sql语句对象  prepareStatement
 *  5.编写sql  执行sql
 *  6.处理结果集
 *  7.释放资源
 *
 *  不足：
 *     1.获取连接的过程繁琐    JdbcUtil
 *     2.查询结果集处理繁琐
 *     3.代码耦合严重   String sql = select  *  from user
 *     4.动态sql  搜索   String  sql  =  select  *  from user where   1==1
 *          username！=null      sql+= " and  username = tom "
 *          age!=null   sql+=  " and age =20"
 *     5.缓存
 *
 *  使用mybatis框架可以很好的解决以上问题
 *
 *
 */
public class TestJDBC {

    public static void main(String[] args) throws SQLException {

        // Class.forName("com.mysql.jdbc.Driver");
        // 创建驱动
        Driver driver = new Driver();
        // 注册驱动
        DriverManager.registerDriver(driver);

        // 准备数据源参数
        String username = "root";
        String password = "root";
        // http://         jdbc:mysql://  协议
        String url = "jdbc:mysql:///java2424?useSSL=true&serverTimezone=GMT%2B8&characterEncoding=utf-8";
        // 获取连接
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println("connection = " + connection);

        // 编写sql
        String sql = "select * from user";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<User> users = new ArrayList<>();
        // 遍历结果集
        while (resultSet.next()){
            String uname = resultSet.getString("username");
            String pwd = resultSet.getString("password");
            User user = new User(1,uname, pwd);
            users.add(user);
        }

        users.forEach(System.out::println);

        // 释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
